package com.sec.android.app.myfiles.module.download.cmd;

import org.puremvc.java.multicore.interfaces.INotification;
import org.puremvc.java.multicore.patterns.command.SimpleCommand;

import android.content.Context;

import com.sec.android.app.myfiles.dialog.ConfirmOmaDialog;
import com.sec.android.app.myfiles.fragment.AbsMyFilesFragment;
import com.sec.android.app.myfiles.info.AppConstants.DownloadHistoryType;
import com.sec.android.app.myfiles.module.download.DownloadFileRecord;

public class OmaConfirmCmd extends SimpleCommand {
    private ConfirmOmaDialog mOmaDialog;

    @Override
    public void execute(INotification notification) {
        Object[] params = (Object[]) notification.getBody();

        Context context = (Context) params[0];
        AbsMyFilesFragment fragment = (AbsMyFilesFragment) params[1];
        DownloadFileRecord record = (DownloadFileRecord) params[2];
        String newPath = findPendingFilePath(record.getPath(), record.getName(), record.getSource());
        if (mOmaDialog != null && mOmaDialog.isShowingSameDialog(newPath)) {
            return;
        }
        if (mOmaDialog != null && mOmaDialog.isDialogShowing()) {
            mOmaDialog.dismissAllowingStateLoss();
            mOmaDialog = null;
        }
        
        mOmaDialog = ConfirmOmaDialog.getDialog(record.getDownloadId(), record.getName(), newPath, record.getVendor(context),
                record.getSize(), record.getVersion(context), record.getMimeType(context), record.getDescription());
        
        if (fragment != null) {
            mOmaDialog.showAllowingStateLoss(fragment.getFragmentManager(), "confirmoma_dialog");
            mOmaDialog.setTargetFragment(mOmaDialog.getParentFragment(), DownloadHistoryType.OK);
        }
    }

    private String chooseName(String name) {
        int indexFrom = name.lastIndexOf('/');
        indexFrom++;

        if (indexFrom < 0) {
            indexFrom = 0;
        }

        int indexTo = name.lastIndexOf('.');
        if (indexTo < 0) {
            indexTo = name.length();
        }

        return name.substring(indexFrom, indexTo);
    }

    private String findPendingFilePath(String path, String displayName, String source) {
        String destFile;
        //int index = path.lastIndexOf('/');

        if (displayName != null) {
            destFile = path + "/" + displayName;
        } else {
            destFile = path + "/" + chooseName(source);
        }

        return destFile;
    }
}
